package com.tjshop.android;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.tjshop.android.adapter.OrderGoodsListAdapter;
import com.tjshop.android.mcv.GlobeVars;
import com.tjshop.android.model.tj.json.CartModel;
import com.tjshop.android.util.SharedPreferencesUtil;
import com.tjshop.android.view.InsideListView;

public class OrderActivity extends BaseActivity implements OnClickListener {

	private TextView totalprice,address_name,address_tel,address,kuaidimingcheng,/*payname,*/bFapiao,liuyan,quehuo,goodsprice,peisongPrice,allprice;
	private LinearLayout selectAddress,selectPeisong,/*selectPay,*/selectFapiao,selectLiuyan,selectQuehuo;
	InsideListView goodsList;
	OrderGoodsListAdapter mAdapter;
	Button submitOrder;
	List<CartModel> intentGoodsList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_detail);
		setTheme(R.style.Theme_Sherlock);
		updateTextViewBar("订单结算", "立即支付", this);
		intentGoodsList = (List<CartModel>) getIntent().getExtras().getSerializable("goodslist");
		initView();
	}
	public void setListViewHeightBasedOnChildren(ListView listView) {

		  // 获取ListView对应的Adapter

		  BaseAdapter listAdapter = (BaseAdapter) goodsList.getAdapter();

		  if (listAdapter == null) {

		   return;

		  }

		  int totalHeight = 0;

		  for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目

		   View listItem = listAdapter.getView(i, null, listView);

		   listItem.measure(0, 0); // 计算子项View 的宽高

		   totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度

		  }

		  ViewGroup.LayoutParams params = listView.getLayoutParams();

		  params.height = totalHeight
		    + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

		  // listView.getDividerHeight()获取子项间分隔符占用的高度

		  // params.height最后得到整个ListView完整显示需要的高度

		  listView.setLayoutParams(params);

		 }
	private void initView() {
		totalprice = (TextView) findViewById(R.id.totalprice);
		address_name = (TextView) findViewById(R.id.add_name);
		address_tel = (TextView) findViewById(R.id.add_tel);
		address = (TextView) findViewById(R.id.address);
		kuaidimingcheng = (TextView) findViewById(R.id.kuaidimingcheng);
		String str = SharedPreferencesUtil.get(getApplicationContext(), "config", "remember_peisong");
		if(str == null){
			kuaidimingcheng.setText("未选择");
		}else{
			kuaidimingcheng.setText(str);
		}
//		payname = (TextView) findViewById(R.id.payname);
		bFapiao = (TextView) findViewById(R.id.bReqFapiao);
		liuyan = (TextView) findViewById(R.id.liuyan);
		quehuo = (TextView) findViewById(R.id.nogoods);
		String str2 = SharedPreferencesUtil.get(getApplicationContext(), "config", "remember_nogoods");
		if(str2 == null){
			quehuo.setText("未选择");
		}else{
			quehuo.setText(str2);
		}
		goodsprice = (TextView) findViewById(R.id.goodsPrice);
		peisongPrice = (TextView) findViewById(R.id.kuaidiPrice);
		allprice = (TextView) findViewById(R.id.allprice);
		selectAddress = (LinearLayout) findViewById(R.id.selectAddress);
		selectAddress.setOnClickListener(this);
		selectPeisong = (LinearLayout) findViewById(R.id.selectpeisong);
		selectPeisong.setOnClickListener(this);
//		selectPay = (LinearLayout) findViewById(R.id.selectpay);
//		selectPay.setOnClickListener(this);
		selectFapiao = (LinearLayout) findViewById(R.id.selectFapiao);
		selectFapiao.setOnClickListener(this);
		selectLiuyan = (LinearLayout) findViewById(R.id.selectLiuyan);
		selectLiuyan.setOnClickListener(this);
		selectQuehuo = (LinearLayout) findViewById(R.id.selectNoGoods);
		selectQuehuo.setOnClickListener(this);
		goodsList = (InsideListView) findViewById(R.id.goodsList);
		submitOrder = (Button) findViewById(R.id.submitorder);
		submitOrder.setOnClickListener(this);
		
		
		mAdapter = new OrderGoodsListAdapter(getApplicationContext(), intentGoodsList, getLayoutInflater());
		goodsList.setAdapter(mAdapter);
		setListViewHeightBasedOnChildren(goodsList);
		float tPrice = 0f;
		for(int i = 0;i<intentGoodsList.size();i++){
			tPrice+=intentGoodsList.get(i).getPrice()*intentGoodsList.get(i).getNum();
		}
		
		totalprice.setText("￥ "+tPrice);
		allprice.setText("￥ "+tPrice);
		goodsprice.setText("￥ "+tPrice);
		if(str == null){
			peisongPrice.setText("0.00");
		}else{
			if(str.equals("顺丰快递")){
				peisongPrice.setText("￥ 22.00");
			}else if(str.equals("韵达快递")){
				peisongPrice.setText("￥ 6.00");
			}else if(str.equals("顺丰快递")){
				peisongPrice.setText("￥15.00");
			}
		}
	}

	@Override
	public boolean handleMessage(Message message) {
		switch (message.what) {
		case 1:
			mProgressDialog.dismiss();
			break;
		case 2:
			mProgressDialog.dismiss();
			initView();
//			getComments();
			break;
		case 3:
			mProgressDialog.dismiss();
			initView();
			break;
		case 4:
			Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
			GlobeVars.CARTNUM++;
			break;
		case 5:
			Toast.makeText(getApplicationContext(), "添加失败", Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public void onClick(View arg0) {
		Intent intent = new Intent();
		switch (arg0.getId()) {
		case R.id.selectAddress:
			intent.setClass(getApplicationContext(), AddressActivity.class);
//			intent.putExtra("url", goodsDetail.getTwDetail());
			startActivity(intent);
			break;
		case R.id.selectFapiao:
			intent.setClass(getApplicationContext(), InvoiceActivity.class);
//			intent.putExtra("url", goodsDetail.getTwDetail());
			startActivity(intent);
			break;
		case R.id.selectLiuyan:
			intent.setClass(getApplicationContext(), PostscriptActivity.class);
//			intent.putExtra("url", goodsDetail.getTwDetail());
			startActivity(intent);
			break;
		case R.id.selectNoGoods:
			intent.setClass(getApplicationContext(), DealWithNoGoodsActivity.class);
//			intent.putExtra("url", goodsDetail.getTwDetail());
			startActivityForResult(intent,REQCODE_NOGOODS);
			break;
//		case R.id.selectpay:
//			intent.setClass(getApplicationContext(), PaySelectActivity.class);
////			intent.putExtra("url", goodsDetail.getTwDetail());
//			startActivity(intent);
//			break;
		case R.id.selectpeisong:
			intent.setClass(getApplicationContext(), DisPatchActivity.class);
//			intent.putExtra("url", goodsDetail.getTwDetail());
			startActivityForResult(intent, REQCODE_PEISONG);
			break;
		default:
			break;
		}
	}
	
	private static final int REQCODE_PEISONG = 1;
	private static final int REQCODE_NOGOODS = 2;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {  
        case REQCODE_PEISONG: 
        	if (resultCode == RESULT_OK) {
        		this.kuaidimingcheng.setText(data.getStringExtra("result"));  
                SharedPreferencesUtil.save(getApplicationContext(), "config", "remember_peisong",data.getStringExtra("result") );
			}
            break;  
        case REQCODE_NOGOODS:
        	if (resultCode == RESULT_OK) {
        		this.quehuo.setText(data.getStringExtra("result"));  
                SharedPreferencesUtil.save(getApplicationContext(), "config", "remember_nogoods",data.getStringExtra("result") );
			}
        	break;
    }  
	}

//	private void addToCart() {
//		if(!GlobeVars.isLogin){
//			startActivity(new Intent(getApplicationContext(), LoginActivity.class));
//			return;
//		}
//		StringRequest stringRequest = new StringRequest(Method.GET,
//				UrlConfigs.URL_ADD_TO_CART + "?gid=" + gid+"&t="+GlobeVars.token+"&num="+1+"&good_attrid=1",
//				new Response.Listener<String>() {
//					@Override
//					public void onResponse(String response) {
//						try {
//							JSONObject obj = new JSONObject(response);
//							if (obj.getInt("r") == 0) {
//								Message message = new Message();
//								message.what = 4;
//								mHandler.sendMessage(message);
//							} else {
//								Message message = new Message();
//								message.what = 5;
//								mHandler.sendMessage(message);
//							}
//
//						} catch (JSONException e) {
//							Message message = new Message();
//							message.what = 5;
//							mHandler.sendMessage(message);
//							e.printStackTrace();
//						}
//
//					}
//				}, new Response.ErrorListener() {
//
//					@Override
//					public void onErrorResponse(VolleyError error) {
//						Message message = new Message();
//						message.what = 5;
//						mHandler.sendMessage(message);
//
//					}
//
//				});
//
//		mQueue.add(stringRequest);
//	}

	

	

}
